<!DOCTYPE HTML>
<html>

<head>
    <title>WEB表单设计器 1.4.2</title>
    <meta name="keyword"
        content="ueditor Formdesign plugins,formdesigner,ueditor扩展,web表单设计器,高级表单设计器,Leipi Form Design,web form设计器,web form designer,javascript jquery ueditor php表单设计器,formbuilder">
    <meta name="description"
        content="Ueditor Web Formdesign Plugins 扩展即WEB表单设计器扩展，它通常在、OA系统、问卷调查系统、考试系统、等领域发挥着重要作用，你可以在此基础上任意修改使功能无限强大！">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="author" content="leipi.org">
    <link href="css/bootstrap/css/bootstrap.css" rel="stylesheet" type="text/css" />
    <link href="../layui/css/layui.css" rel="stylesheet" type="text/css"/>
    <!--[if lte IE 6]>
    <link rel="stylesheet" type="text/css" href="css/bootstrap/css/bootstrap-ie6.css">
    <![endif]-->
    <!--[if lte IE 7]>
    <link rel="stylesheet" type="text/css" href="css/bootstrap/css/ie.css">
    <![endif]-->
    <link href="css/site.css" rel="stylesheet" type="text/css" />
    <link href="css/index.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="css/zTreeStyle.css" type="text/css">
</head>

<body>
    <div class="container">
        <div class="form-library">
            <button class="layui-btn layui-btn-normal T-btn openForm" data-target='openForm'>业务表单列表</button>
            <div class="select-nodes-list scroll">
                <ul></ul>
            </div>
        </div>
        <div class="span10 clearfix">
            <div id="myFormDesign" class="edui-default myFormDesign">
                <div class="btn-group">
                    <button class="layui-btn layui-btn-normal layui-btn-sm create-btn" onclick="createTab()">新建</button>
                    <button class="layui-btn layui-btn-normal layui-btn-sm T-btn pre-btn" id="preview"><i class="layui-icon layui-icon-list"></i>预览</button>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" style="width: 100px;padding: 9px 0;">业务表单名称：</label>
                    <div class="layui-input-block" style="margin-left: 100px;">
                        <input type="text" class="layui-input custom-tablename-input caption" autocomplete="off" name="tablename" />
                    </div>
                </div>
            </div>
            <!-- <div class="metadata-box">
                <div class="layui-card-header" style="height: 80px;">
                    <div class="layui-inline">
                        <input type="text" name="meta" class="layui-input custom-meta-input" autocomplete="off" placeholder="请输入查询字段">
                        <button type="button" class="layui-btn layui-btn-xs custom-meta-btn" onclick="selectMeta()">
                            <i class="layui-icon layui-icon-search"></i>
                        </button>
                    </div>
                    <button class="insertMeta layui-btn layui-btn-normal layui-btn-sm" title="插入元数据" id="insertMeta" onclick="insertMeta()">插入</button>
                </div>
                <ul id="metaTree" class="ztree meta-tree"></ul>
            </div> -->
            <textarea id="del-form-container" style="display: none;"></textarea>
        </div>
    </div>
<script type="text/javascript" charset="utf-8" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" charset="utf-8" src="../layui/layui.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jquery.cookie.js"></script>
<script type="text/javascript" charset="utf-8" src="js/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="js/ueditor/ueditor.all.js"> </script>
<script type="text/javascript" charset="utf-8" src="js/ueditor/lang/zh-cn/zh-cn.js"></script>
<script type="text/javascript" charset="utf-8" src="js/ueditor/formdesign/leipi.formdesign.v4.js"></script>
<!-- 兼容IE8/9 -->
<!-- [if let IE9] -->
<script type="text/javascript" src="js/html5shiv.min.js"></script>
<script type="text/javascript" src="js/respond.min.js"></script>
<!-- endif -->
<script type="text/javascript" charset="UTF-8" src="js/slidebar.js"></script>

<script type="text/javascript" src="js/jquery.ztree.core.js"></script>
<script type="text/javascript" src="js/jquery.ztree.excheck.js"></script>
<script type="text/javascript" src="js/jquery.ztree.exhide.js"></script>
<!-- script start-->
<script type="text/javascript">
    var layer = null,
        delFormMsg = [],
        searchInput = document.querySelector('.custom-tablename-input');

    layui.use(['layer'], function(){
        layer = layui.layer;
    });

    //indexOf不兼容IE
    if (!Array.prototype.indexOf)
    {
    Array.prototype.indexOf = function(elt /*, from*/)
    {
        var len = this.length >>> 0;


        var from = Number(arguments[1]) || 0;
        from = (from < 0)
            ? Math.ceil(from)
            : Math.floor(from);
        if (from < 0)
        from += len;


        for (; from < len; from++)
        {
        if (from in this &&
            this[from] === elt)
            return from;
        }
        return -1;
    };
    }

    var setting = {
        data: {
            key: {
                children: "child",
                name: "text",
            },
            simpleData: {
                enable: true
            }
        },
        check: {
            enable: true,
            chkStyle: "checkbox",
            chkboxType: {"Y": "s", "N": "ps"}
        },
        callback: {
            onClick: zTreeOnClick
        }
    };

    if (!document.querySelectorAll) {
        document.querySelectorAll = function (selectors) {
            var style = document.createElement('style'), elements = [], element;
            document.documentElement.firstChild.appendChild(style);
            document._qsa = [];

            style.styleSheet.cssText = selectors + '{x-qsa:expression(document._qsa && document._qsa.push(this))}';
            window.scrollBy(0, 0);
            style.parentNode.removeChild(style);

            while (document._qsa.length) {
                element = document._qsa.shift();
                element.style.removeAttribute('x-qsa');
                elements.push(element);
            }
            document._qsa = null;
            return elements;
        };
    }

    var metaSet = {
        data: {
            key: {
                children: "child",
                name: "text",
            },
            simpleData: {
                enable: true
            }
        },
        view: {
            showIcon: false,
            showLine: false
        },
        check: {
            enable: true,
            chkStyle: "checkbox",
            chkboxType: {"Y": "s", "N": "ps"}
        },
        callback: {
            onClick: metaTreeClick
        }
    }

    getTree(); 
    getMetaData(); 

    //获取表单树
    function getTree() {
        $.ajax({
            url: '../myapi/DC/api/rest/web/custom/GetFormList',
            type: 'post',
            data: {
                app_id: 'dsgfdg45',
                access_token: layui.data('layuiAdmin').access_token
            },
            success: function (res) {
                if (res.retcode == '0') {
                    zNodes = res.data;
                    if(parent.selectTable && parent.selectTable.length > 0) {
                        $.each(parent.selectTable, function(i) {
                            $.each(res.data, function(index) {
                                if(res.data[index].id === parent.selectTable[i].form_id) {
                                    res.data[index].checked = true;
                                }
                            })
                        })
                    }
                    window.iframeZtree = $.fn.zTree.init($("#treeDemo"), setting, zNodes);
                    var nodes = iframeZtree.getNodes();
                    if(nodes.length > 0){
                        iframeZtree.expandAll(true);
                        iframeZtree.selectNode(nodes[0]);
                    }
                }
            }
        })
    }

    //浏览器是否是ie
	function isIE() { //ie?  
		if (!!window.ActiveXObject || "ActiveXObject" in window)  
			{ return true; }  
		else  
			{ return false; }  
	}

    //获取元数据
    function getMetaData(text){
        var text = text ? text : '';
        $.ajax({
            url: '../myapi/DC/api/rest/web/custom/GetMetaData',
            type: 'post',
            data: {
                text: text,
                access_token: layui.data('layuiAdmin').access_token
            },
            success: function(res){
                var mNodes = res.data
                if(res.retcode == '0'){
                    window.metaTree = $.fn.zTree.init($("#metaTree"), metaSet, mNodes);
                }
            }
        })
    }

    //初始化选择表单列表
    function showSelectNodes(chooseNodes){
        var lihtml = '';
        if(chooseNodes.length > 0){
            for(var i = 0; i < chooseNodes.length; i++){
                if(i == 0){
                    lihtml += "<li class='liactive' title='"+chooseNodes[i].text+"' id='"+chooseNodes[i].id+"' data-formid='"+chooseNodes[i].id+"' data-model='choose' data-tablename='"+chooseNodes[i].tablename+"' data-formtypeid='"+chooseNodes[i].formtype_id+"' data-html='"+chooseNodes[i].html+"'><span>"+chooseNodes[i].text+"</span><i class='layui-icon layui-icon-close-fill T-btn' data-target='del-form'></i></li>"
                }else{
                    lihtml += "<li data-model='choose' title='"+chooseNodes[i].text+"' id='"+chooseNodes[i].id+"' data-formid='"+chooseNodes[i].id+"' data-tablename='"+chooseNodes[i].tablename+"' data-formtypeid='"+chooseNodes[i].formtype_id+"'  data-html='"+chooseNodes[i].html+"'><span>"+chooseNodes[i].text+"</span><i class='layui-icon layui-icon-close-fill T-btn' data-target='del-form'></i></li>"
                }
            }
            $('.select-nodes-list ul').append(lihtml);
            $('.select-nodes-list ul li').eq(0).click();
        }
        layer.close(form_index);
    }
    
    //新建表格
    function createTab(){
        $('#insertMeta').removeClass('layui-btn-disabled');
        $('#insertMeta').removeAttr('disabled');
        $('.caption').attr('readonly') && $('.caption').removeAttr('readonly');
        var prevHtml = leipiEditor.getContent();
        $('.select-nodes-list ul li').each(function(index, item){
            item.getAttribute('class') == 'liactive' && item.setAttribute('data-html', prevHtml);
        });
        layer.prompt({
            formType: 0,
            title: '<i class="formFill-icon"></i><span style="color:#FFF;">请输入表单名</span>',
            area: ['200px', '20px']
        }, function(value, index, elem){
            if(!!$.trim(value)){
                // var opt = {border: 1, numCols: 2, numRows: 2, tdvalign: "center", tdwidth: 200},
                var opt = {border: 1, numCols: 2, numRows: 1, tdvalign: "center", tdwidth: 200},
                    html = [],
                    rowsNum = opt.numRows,
                    colsNum = opt.numCols,
                    randomId = 't_' + createUniqueId(1); //给table表格生成随机id
                for (var r = 0; r < rowsNum; r++) {
                    html.push('<tr' + (r == 0 ? ' class="firstRow"':'') + '>');
                    for (var c = 0; c < colsNum; c++) { 
                        if(r == 0){
                            var thId = 'v_' + createUniqueId(1); 
                            html.push('<th model="insert" width="' + opt.tdwidth + 'px" id="'+thId+'" data_type="varchar" data_length="64" isfill="0" query="1"></th>');
                        }
                        else{
                            html.push('<td width="' + opt.tdwidth + 'px" align="' + opt.tdvalign + '"></td>');
                        }
                    }
                    html.push('</tr>')
                }
                var tableHtml = '<table id="'+randomId+'" model="insert"><tbody>' + html.join('') + '</tbody></table>';
                addFormList(tableHtml, 'insert', value);
                leipiEditor.setContent(tableHtml);
                layer.close(index);
            }else{
                layer.msg('请填写表格的标题', {time: 1000});
            }
        })
    }

    //删除表格
    function delTab(type){
        layer.confirm('确定删除表格吗？', {
            btn: ['确定', '取消'],
            btn2: function(index){ //取消
                
            }
        }, function(index){ //确定
            var content = leipiEditor.getContent();
            var div = document.createElement('div');
            div.innerHTML = content;
            var model = div.querySelector('table').getAttribute('model');
            if(model != 'insert'){
                leipiFormDesign.fnCheckForm(type); //从表单库删除
            }else{
                leipiEditor.setContent('');  //本地直接清空而已
            }
            layer.close(index);
        })
    }
    
    //保存表单
    function saveTab(type){
        leipiFormDesign.fnCheckForm(type);
    }

    //添加新建表单
    function addFormList(html , model, formname){
        $('.select-nodes-list ul li').each(function(index, item){
            item.removeAttribute('class');
        })
        var property = JSON.stringify(copyTab('copy','insert')),
            lihtml = "<li class='liactive' title='"+formname+"' data-model='"+model+"' data-formid='' data-html='"+html+"' data-params='"+property+"'><span>"+formname+"</span><i class='layui-icon layui-icon-close-fill T-btn' data-target='del-form'></i></li>";
        $('.select-nodes-list ul').append(lihtml);
        $('.caption').val(formname);
    }

    //复制当前表单
    function copyTab(type,flag){
        var property = leipiFormDesign.fnCheckForm(type,flag);
        return property;
    }

    var property = null;
    $('#copyTab').click(function(){
        var text = $(this).text();
        if(text == '复制'){
            property = copyTab('copy');
            if(property){
                $(this).text('粘贴');
            }
        }else{
            var selectNodes = iframeZtree.getSelectedNodes();
            var isParent = selectNodes[0].isParent;
            if(isParent){
                property.model = 'insert';
                var newgrid = JSON.parse(property.grid);
                for(var i = 0; i < newgrid.length; i++){
                    newgrid[i].model = 'insert';
                }
                property.grid = JSON.stringify(newgrid);
                leipiFormDesign.updateForm(property);
                $(this).text('复制');
            }else{
                layer.msg('已存在表单，请粘贴至相应文件夹下', {time: 1000});
            }
        }
    })

    //监听表单名输入框
    if (document.all) { //是IE浏览器（兼容IE8）
        searchInput.onpropertychange = function () {
            handleNameChange(searchInput.value);
        }
    }else { // 非IE
        searchInput.addEventListener('input', function () {
            handleNameChange(searchInput.value);
        })
    }

    //按钮点击事件
    $('.container').delegate('.T-btn', 'click', function(e){
        var target = $(this).attr('data-target');
        if(target == 'openForm'){
            removeCheck();
            var form_index = layer.open({
                id: 'formLibrary',
                title: '<i class="formFill-icon"></i><span style="color:#FFF;">业务表单列表</span>',
                type: 1,
                offset: '5px',
                shadeClose: true,
                area: ['725px', '480px'],
                content: $('.formTreeList'),
                success: function(layero, index){
                    $(layero).on('click', '#insertForm', function(){
                        var checkNodes = iframeZtree.getCheckedNodes(true),
                            exitNodes = $('.select-nodes-list ul li') || [],
                            insertNodes = [],
                            exitNodesId = [];
                        for(var i = 0; i < checkNodes.length; i++){
                            if(!checkNodes[i].isParent){
                                if(exitNodes && exitNodes.length > 0){
                                    $.each(exitNodes, function(index, item){
                                        exitNodesId.push(item.getAttribute('id'));
                                    })
                                    if(exitNodesId.indexOf(checkNodes[i].id) < 0){
                                        insertNodes.push(checkNodes[i]);
                                    }
                                }else{
                                    insertNodes.push(checkNodes[i]);
                                }
                            }
                        }
                        showSelectNodes(insertNodes);
                    })
                }
            });
            window.form_index = form_index;
        }else if(target == 'del-form'){
            e.stopPropagation();
            var li = $(this).parent('li'),
                model = li.attr('data-model'),
                index = li.index();
            if(model == 'normal'){
                var id = li.attr('id');
                delFormMsg.push({ form_id: id, model: 'del' });
                $('#del-form-container').text(JSON.stringify(delFormMsg));
            } 
            $('.select-nodes-list ul li').eq(index).remove();
            $('.caption').val('');
            leipiEditor.setContent('');
		}
    })

    //键盘绑定事件
    $(document).keydown(function(e){
        if(e.keyCode && e.keyCode == '13'){
            $('.custom-meta-btn').trigger('click');
        }
    })

    //列表切换展示
    $('.select-nodes-list ul').delegate('li', 'click', function(){
        var html = $(this).attr('data-html'),
            readOnly = $(this).attr('data-select') ? $(this).attr('data-select') : '0';
            arr = [],
            tholdName = [], //清空数组
            editable = $(this).attr('del');
            window.basename = $(this).attr('data-tablename');
            window.baseid = $(this).attr('data-id');
        $(this).addClass('liactive');
        $(this).siblings().removeClass('liactive');
        $('.caption').val($(this).text());
        readOnly === '1' ? $('.caption').attr('readonly', 'readonly') : $('.caption').removeAttr('readonly');
        if (html) {
            var prevHtml = leipiEditor.getContent();
            if(prevHtml){ setTable(prevHtml) }
            var div = document.createElement('div'),
                nowHtml = $(this).attr('data-html');
            div.innerHTML = nowHtml;
            var table = div.querySelector('table'),
                th = div.querySelectorAll('th');
            for(var j = 0; j < th.length; j++){
                tholdName.push(th[j].innerText);
                if(th[j].getAttribute('isdel') == null){
                    arr.push(th[j]);
                }
            }
            $(this).attr('data-html', div.innerHTML);
            if(editable && editable == '0'){ 
                var table = div.querySelector('table');
                table.setAttribute('contenteditable', 'false');
                $('#insertMeta').addClass('layui-btn-disabled');
                $('#insertMeta').attr('disabled', 'disabled');
            }else{
                $('#insertMeta').removeClass('layui-btn-disabled');
                $('#insertMeta').removeAttr('disabled');
            }
            leipiEditor.setContent(div.innerHTML);
            $.cookie('colNum', arr.length);
        }
    });

    //绑定表单库表单
    function setSelectCheck(){
        var selectList = $('.select-nodes-list ul li');
        var selectId = []; //已选择的表单id集合
        var treeNodes = iframeZtree.transformToArray(iframeZtree.getNodes());
        $.each(selectList, function(index, item){
            selectId.push(item.getAttribute('data-formid'));
        })
        if(selectId.length > 0){
            for(var i = 0; i < selectId.length; i++){
                for(var j = 0; j < treeNodes.length; j++){
                    if(selectId[i] == treeNodes[j].id){
                        iframeZtree.checkNode(treeNodes[j], true, true)
                    }
                }
            }
        }
    }

    //设置修改后html代码到表单上
    function setTable(newHtml){
        var newDiv = document.createElement('div');
        newDiv.innerHTML = newHtml;
        var id = newDiv.querySelector('table').getAttribute('id');
        $('.select-nodes-list ul li').each(function(index, item){
            var div = document.createElement('div');
            div.innerHTML = item.getAttribute('data-html');
            var oldId = div.querySelector('table').getAttribute('id');
            if(oldId == id){ item.setAttribute('data-html', newHtml); }
        })
    }

    /*修改表单名
    *@param name 修改的表单名称
    */
    function  handleNameChange(name){
        var formList = $('.select-nodes-list ul li');
        if(formList && formList.length > 0){
            var chgLi = $('.select-nodes-list .liactive span');
            if(!!name){ chgLi.text(name);$('.select-nodes-list .liactive').attr('title', name); }
            else{ layer.msg('表单名称为必填项');chgLi.text('请填写表单名称'); }
        }
    }


    //创建元素
    function createEle(ele, html){
        var element = document.createElement(ele);
        element.innerHTML = html;
        return element;
    }

    //取消选中状态
    function removeCheck(){
        iframeZtree.checkAllNodes(false);
    }
    
    //获取表单参数
    function reloadTab(html, type){
        var property = leipiFormDesign.getFormInfo(html, type);
        return property;
    }

    //生成随机数
    function createUniqueId(prefix) {
        return (prefix || '') + new Date().getTime().toString(36) + Math.random().toString(36).slice(2);
    }

    var basename = ''; //当前表单名
    var baseid = ''; //当前表单id
    var tholdName = []; //当前表头修改前的值

    function zTreeOnClick(event, treeId, treeNode) {
        var isParent = treeNode.isParent; //判断是否为父亲节点
        tholdName = []; //清空数组
        if (!isParent) {
            var id = treeNode.id;
            var html = treeNode.html;
            var arr = [];
            basename = treeNode.tablename; //父节点表单名
            baseid = treeNode.id; //父节点表单id
            if (html) {
                var div = document.createElement('div');
                div.innerHTML = html;
                var table = div.querySelector('table');
                var th = div.querySelectorAll('th');
                for(var j = 0; j < th.length; j++){
                    tholdName.push(th[j].innerText);
                    th[j].setAttribute('model', 'normal'); //列状态也为normal
                    if(th[j].getAttribute('isdel') == null){
                        arr.push(th[j]);
                    }
                }
                table.setAttribute('model', 'normal'); //加载表格默认状态为normal
                leipiEditor2.setContent(div.innerHTML);
                $.cookie('colNum', arr.length);
            }
        }else{
            leipiEditor.setContent('');
        }
    }

    //元数据回调事件
    function metaTreeClick(event, treeId, treeNode){
    }

    //插入元数据
    function insertMeta(){
        var template = leipiEditor.getContent(),
            div = document.createElement('div');
            div.innerHTML = template;
        var hasTh = div.querySelectorAll('th[data_type]'),
            Nodes = [],
            checkMeta = metaTree.getCheckedNodes(true),
            nodeList = [],
            selectNodes = [];

        $.each(checkMeta, function(index, item){
            if(!item.isParent){
                Nodes.push(item);
            }
        })
        $.each(hasTh, function(index, item){
            $.each(Nodes, function(i, node){
                if(item.getAttribute('id') == node.fieldenglish){
                    nodeList.push(node);
                }
            })
        })
        if(nodeList.length == 0){
            selectNodes = Nodes;
        }else{
            if(nodeList && nodeList.length == 1){
                layer.msg(nodeList[0].text+'已存在');
                return false ;
            }else{
                layui.each(nodeList, function(index, item){
                    layui.each(Nodes, function(k, node){
                        if(node.fieldenglish == item.fieldenglish){
                            Nodes.splice(k, 1);
                        }
                    })
                })
                selectNodes = Nodes;
                layer.msg('已忽略相同字段', {time: 1500});
            }
        }    
        if(selectNodes && selectNodes.length > 0){
            if(hasTh.length > 0){
                var oldlen = parseInt($.cookie('colNum'));
                var insertTh = div.querySelector('th[model="normal"]') || div.querySelector('th[model="insert"]'),
                    row = insertTh.parentNode;
                for(var i = 0, len = selectNodes.length; i < len; i++){
                    var th = document.createElement('th');
                    th.innerText = selectNodes[i].text;
                    th.setAttribute('model', 'insert'); 
                    th.setAttribute('data_type', selectNodes[i].datatype);
                    th.setAttribute('data_length', selectNodes[i].length);
                    th.setAttribute('isfill', '0');
                    th.setAttribute('query', '0');
                    th.setAttribute('id', selectNodes[i].fieldenglish);
                    th.setAttribute('comdataitemid', selectNodes[i].comdataitemid);
                    row.appendChild(th);
                }
                leipiEditor.setContent(div.innerHTML);
            }else{
                var header = $('.caption').val();
                if(!!header){
                    var opt = {border: 1, numCols: selectNodes.length, numRows: 2, tdvalign: "center", tdwidth: 200};
                    loadMetaTable(opt, header, selectNodes);
                }else{
                    layer.prompt({
                        formType: 0,
                        title: '<i class="formFill-icon"></i><span style="color:#FFF;">表格标题</span>',
                        area: ['200px', '20px']
                    }, function(value, index, elem){
                        var opt = {border: 1, numCols: selectNodes.length, numRows: 2, tdvalign: "center", tdwidth: 200},
                            html = loadMetaTable(opt, value, selectNodes);
                        addFormList(html, 'insert', value);
                        layer.close(index);
                    })
                }
            }
        }else {
            layer.msg('请选择字段插入', {time: 1500});
        }
        var prevHtml = leipiEditor.getContent();
        if(prevHtml){ setTable(prevHtml) }
        metaTree.checkAllNodes(false); 
    }

    //查询字段
    function selectMeta(){
        var metaText = $('.custom-meta-input').val();
        getMetaData($.trim(metaText));
    }

    //元数据加载表格
    function loadMetaTable(opt, value, Nodes){
        var html = [],
            rowsNum = opt.numRows,
            colsNum = opt.numCols,
            tableHtml = '',
            randomId = 't_' + createUniqueId(1); 
        $.cookie('colNum', colsNum);
        if(!!$.trim(value)){
            for (var r = 0; r < rowsNum; r++) {
                html.push('<tr' + (r == 0 ? ' class="firstRow"':'') + '>');
                for (var c = 0; c < colsNum; c++) { 
                    if(r == 0){
                        var thId = 'v_' + createUniqueId(1); 
                        html.push('<th model="insert" width="' + opt.tdwidth + 'px" data_type="'+Nodes[c].datatype+'" data_length="'+Nodes[c].length+'" comdataitemid="'+Nodes[c].comdataitemid+'" id="'+Nodes[c].fieldenglish+'" isfill="0" query="0">'+Nodes[c].text+'</th>');
                    }
                    else{
                        html.push('<td width="' + opt.tdwidth + 'px" align="' + opt.tdvalign + '"></td>');
                    }
                }
                html.push('</tr>')
            }
            tableHtml = '<table id="'+randomId+'" model="insert"><tbody>' + html.join('') + '</tbody></table>';
            leipiEditor.setContent(tableHtml);
        }else{
            layer.msg('请配置表单名', {time: 1500});
        }
        return tableHtml;
    }

    var leipiEditor = UE.getEditor('myFormDesign', {
        allowDivTransToP: false, //阻止转换div 为p
        toolleipi: true, //是否显示，设计器的 toolbars
        textarea: 'design_content',
        //这里可以选择自己需要的工具按钮名称,此处仅选择如下五个
        toolbars: [
            [
                // 'bold', 'italic','underline', 'removeformat', '|',
                // 'forecolor', 'backcolor',  '|',
                // 'fontfamily', 'fontsize'
            ]
        ],
        //focus时自动清空初始化时的内容
        //autoClearinitialContent:true,
        //关闭字数统计
        wordCount: false,
        //关闭elementPath
        elementPathEnabled: false,
        //默认的编辑区域高度
        initialFrameHeight: 500
        ,iframeCssUrl:"css/bootstrap/css/bootstrap.css" //引入自身 css使编辑器兼容你网站css
        //更多其他参数，请参考ueditor.config.js中的配置项
    });

    var leipiFormDesign = {
        /*执行控件*/
        exec: function (method) {
            leipiEditor.execCommand(method);
        },
        /*
            Javascript 解析表单
            template 表单设计器里的Html内容
            fields 字段总数
        */
        parse_form: function (template, fields) {
            //正则  radios|checkboxs|select 匹配的边界 |--|  因为当使用 {} 时js报错
            var preg =
                /(\|-<span(((?!<span).)*leipiplugins=\"(radios|checkboxs|select)\".*?)>(.*?)<\/span>-\||<(img|input|textarea|select).*?(<\/select>|<\/textarea>|\/>))/gi,
                preg_attr = /(\w+)=\"(.?|.+?)\"/gi,
                preg_group = /<input.*?\/>/gi;
            if (!fields) fields = 0;

            var template_parse = template,
                template_data = new Array(),
                add_fields = new Object(),
                checkboxs = 0;

            var pno = 0;
            template.replace(preg, function (plugin, p1, p2, p3, p4, p5, p6) {
                var parse_attr = new Array(),
                    attr_arr_all = new Object(),
                    name = '',
                    select_dot = '',
                    is_new = false;
                var p0 = plugin;
                var tag = p6 ? p6 : p4;
                if (tag == 'radios' || tag == 'checkboxs') {
                    plugin = p2;
                } else if (tag == 'select') {
                    plugin = plugin.replace('|-', '');
                    plugin = plugin.replace('-|', '');
                }
                plugin.replace(preg_attr, function (str0, attr, val) {
                    if (attr == 'name') {
                        if (val == 'leipiNewField') {
                            is_new = true;
                            fields++;
                            val = 'data_' + fields;
                        }
                        name = val;
                    }

                    if (tag == 'select' && attr == 'value') {
                        if (!attr_arr_all[attr]) attr_arr_all[attr] = '';
                        attr_arr_all[attr] += select_dot + val;
                        select_dot = ',';
                    } else {
                        attr_arr_all[attr] = val;
                    }
                    var oField = new Object();
                    oField[attr] = val;
                    parse_attr.push(oField);
                })
                if (tag == 'checkboxs') /*复选组  多个字段 */ {
                    plugin = p0;
                    plugin = plugin.replace('|-', '');
                    plugin = plugin.replace('-|', '');
                    var name = 'checkboxs_' + checkboxs;
                    attr_arr_all['parse_name'] = name;
                    attr_arr_all['name'] = '';
                    attr_arr_all['value'] = '';

                    attr_arr_all['content'] =
                        '<span leipiplugins="checkboxs"  title="' + attr_arr_all[
                            'title'] + '">';
                    var dot_name = '',
                        dot_value = '';
                    p5.replace(preg_group, function (parse_group) {
                        var is_new = false,
                            option = new Object();
                        parse_group.replace(preg_attr, function (str0, k, val) {
                            if (k == 'name') {
                                if (val == 'leipiNewField') {
                                    is_new = true;
                                    fields++;
                                    val = 'data_' + fields;
                                }

                                attr_arr_all['name'] += dot_name + val;
                                dot_name = ',';

                            } else if (k == 'value') {
                                attr_arr_all['value'] += dot_value +
                                val;
                                dot_value = ',';

                            }
                            option[k] = val;
                        });

                        if (!attr_arr_all['options']) attr_arr_all['options'] =
                            new Array();
                        attr_arr_all['options'].push(option);
                        var checked = option['checked'] != undefined ?
                            'checked="checked"' : '';
                        attr_arr_all['content'] +=
                            '<input type="checkbox" name="' + option['name'] +
                            '" value="' + option['value'] + '"  ' + checked +
                            '/>' + option['value'] + '&nbsp;';

                        if (is_new) {
                            var arr = new Object();
                            arr['name'] = option['name'];
                            arr['leipiplugins'] = attr_arr_all['leipiplugins'];
                            add_fields[option['name']] = arr;

                        }

                    });
                    attr_arr_all['content'] += '</span>';

                    //parse
                    template = template.replace(plugin, attr_arr_all['content']);
                    template_parse = template_parse.replace(plugin, '{' + name + '}');
                    template_parse = template_parse.replace('{|-', '');
                    template_parse = template_parse.replace('-|}', '');
                    template_data[pno] = attr_arr_all;
                    checkboxs++;

                } else if (name) {
                    if (tag == 'radios') /*单选组  一个字段*/ {
                        plugin = p0;
                        plugin = plugin.replace('|-', '');
                        plugin = plugin.replace('-|', '');
                        attr_arr_all['value'] = '';
                        attr_arr_all['content'] = '<span leipiplugins="radios" name="' +
                            attr_arr_all['name'] + '" title="' + attr_arr_all['title'] +
                            '">';
                        var dot = '';
                        p5.replace(preg_group, function (parse_group) {
                            var option = new Object();
                            parse_group.replace(preg_attr, function (str0, k,
                                val) {
                                if (k == 'value') {
                                    attr_arr_all['value'] += dot + val;
                                    dot = ',';
                                }
                                option[k] = val;
                            });
                            option['name'] = attr_arr_all['name'];
                            if (!attr_arr_all['options']) attr_arr_all[
                                'options'] = new Array();
                            attr_arr_all['options'].push(option);
                            //if(!option['checked']) option['checked'] = '';
                            var checked = option['checked'] != undefined ?
                                'checked="checked"' : '';
                            attr_arr_all['content'] +=
                                '<input type="radio" name="' + attr_arr_all[
                                    'name'] + '" value="' + option['value'] +
                                '"  ' + checked + '/>' + option['value'] +
                                '&nbsp;';

                        });
                        attr_arr_all['content'] += '</span>';

                    } else {
                        attr_arr_all['content'] = is_new ? plugin.replace(
                            /leipiNewField/, name) : plugin;
                    }
                    template = template.replace(plugin, attr_arr_all['content']);
                    template_parse = template_parse.replace(plugin, '{' + name + '}');
                    template_parse = template_parse.replace('{|-', '');
                    template_parse = template_parse.replace('-|}', '');
                    if (is_new) {
                        var arr = new Object();
                        arr['name'] = name;
                        arr['leipiplugins'] = attr_arr_all['leipiplugins'];
                        add_fields[arr['name']] = arr;
                    }
                    template_data[pno] = attr_arr_all;


                }
                pno++;
            })
            var parse_form = new Object({
                'fields': fields, //总字段数
                'template': template, //完整html
                'parse': template_parse, //控件替换为{data_1}的html
                'data': template_data, //控件属性
                'add_fields': add_fields //新增控件
            });
            return JSON.stringify(parse_form);
        },
        /*type  =  save 保存设计 versions 保存版本  close关闭 */
        fnCheckForm: function (type,flag) {   
            if (leipiEditor.queryCommandState('source')) leipiEditor.execCommand('source'); //切换到编辑模式才提交，否则有bug
            if (leipiEditor.hasContents()) {
                leipiEditor.sync();/*同步内容*/
                //获取表单设计器里的内容
                formeditor = leipiEditor.getContent();
                var template = document.createElement('div');
                template.innerHTML = formeditor;
                    var tablename = $('.caption').val(),
                        formId = template.querySelector('table').getAttribute('id'); 
                    if (tablename) {
                        var ths = template.querySelectorAll('.firstRow th');
                        var property = new Object();
                        var grid = [];
                        var thnewName = [];
                        if (ths.length > 0) {
                            for (var i = 0; i < ths.length; i++) {
                                var obj = new Object();
                                obj.form_typeid = formId; //字段所属表格或表单id
                                obj.fieldstate = '1'; //字段状态  正常使用为1,被删除为0
                                var text = ths[i].innerText; //字段中文名称
                                thnewName.push(text);
                                var colId = ths[i].getAttribute('id'); //字段英文名称
                                if (text) obj.fieldname = text;
                                if (colId) obj.fieldenglish = colId;
                                var sort = ths[i].getAttribute('table_sort');
                                var query = ths[i].getAttribute('query');
                                var sum = ths[i].getAttribute('sum');
                                var average = ths[i].getAttribute('average');
                                var count = ths[i].getAttribute('count');
                                var colSum = ths[i].getAttribute('col_sum');
                                var colAverage = ths[i].getAttribute('col_average');
                                var colCount = ths[i].getAttribute('col_count');
                                var dataType = ths[i].getAttribute('data_type'); //字段类型
                                var dataLength = ths[i].getAttribute('data_length'); //字段长度
                                var isFill = ths[i].getAttribute('isfill'); //必填
                                var thModel = ths[i].getAttribute('model'); //内层model属性
                                var fill_field=ths[i].getAttribute('fill_field');//自动填充设置

                                if (sort) obj.sortno = sort; //排序
                                else {obj.sortno = 'null'};
                                if (dataLength) obj.length = dataLength; //字段长度
                                if (fill_field) obj.fill_field = fill_field;//自动填充设置
                                if (query) obj.queryno = query; //查询
                                if (average == '1' || sum == '1' || count == '1' || colSum ==
                                    '1' || colAverage == '1' || colCount == '1') obj.stacno =
                                    '1';
                                else obj.stacno = '0';
                                if (dataType) obj.datatype = dataType;
                                if (isFill) obj.nonull = isFill;
                                if(thModel) obj.model = thModel;
                                grid.push(obj);
                            }
                        }
                        leipiFormDesign.setUptModel(tholdName, thnewName, template);
                        var tableModel = template.querySelector('table').getAttribute('model'); //外层model属性
                        property.formname = tablename;
                        property.html = formeditor;
                        if(type == 'del'){
                            property.model = 'del';
                        }else{
                            property.model = tableModel;
                        }
                        property.grid = JSON.stringify(grid); //将grid数组转换成字符串
                        if(tableModel != 'insert') {
                            property.tablename = window.basename;
                            property.id = window.baseid;
                        };
                        if(type == 'copy') {
                            return property;
                            return false;
                        }
                        leipiFormDesign.updateForm(property);
                    } else {
                        layer.msg('表单名称不能为空！')
                        return false;
                    }
            }else {
                if(!flag){
                    layer.msg('表单内容不能为空！')
                     return false;
                }
               
            }
        },
        //新增、更新、删除、复制表单
        updateForm: function (params) {
            var selectNodes = iframeZtree.getSelectedNodes();
            var formtypeid = '';
            if(params.model == 'insert'){
                formtypeid = selectNodes[0].id;  //新增
            }else{
                formtypeid = selectNodes[0].formtype_id; //修改、删除
            }
            if(formtypeid != ''){ params.formtype_id = formtypeid}
            params.access_token = layui.data('layuiAdmin').access_token;
            $.ajax({
                url: '../myapi/DC/api/rest/web/custom/FormMaintan', 
                type: 'post',
                data: params,
                success: function (res) {
                    if(res.retcode == '0'){
                        var data = res.data;
                        if(data.retcode == 1){
                            getTree(); //重新加载表单树形结构
                            if(params.model == 'del'){
                                leipiEditor.setContent(''); //删除成功后清空编辑器
                            }
                            if(params.model == 'insert'){ //新增表格成功后，右侧列表显示
                                var prehtml = $('.select-nodes-list ul').html();
                                var newLi = createEle('li', params.formname);
                                var allListHtml =  prehtml+newLi.outerHTML;
                                $('.select-nodes-list ul').html(allListHtml);
                            }   
                            layer.msg(data.retmsg, {time: 1000});
                            return 'yes';
                        }else{
                            layer.msg(data.retmsg, {time: 1000});
                        }
                    }else{
                        layer.msg(res.retmsg, {time: 1000});
                    }
                }
            })
        },
        getFormInfo: function (html, type) {  
            if (leipiEditor.queryCommandState('source')) leipiEditor.execCommand('source'); //切换到编辑模式才提交，否则有bug
            if (leipiEditor.hasContents()) {
                leipiEditor.sync();/*同步内容*/
                formeditor = leipiEditor.getContent();
                var template = document.createElement('div');
                template.innerHTML = formeditor;
                    var tablename = $('.caption').val(),
                        formId = template.querySelector('table').getAttribute('id'); 
                         // 下拉框数据
                   var supcontentObj={};
                    if (!!tablename) {
                        var ths = template.querySelectorAll('th'),
                            property = {}, grid = [], cols = [];
                            thnewName = [];
                        if (ths && ths.length > 0) {
                            ths = leipiFormDesign.setThsOrder(template, leipiFormDesign.getValueThs(template));
                            var cols = leipiFormDesign.getCols(template);
                            for (var i = 0; i < ths.length; i++) {
                                    var obj = new Object();
                                    var text = ths[i].innerText; //字段中文名称
                                    if (text) obj.fieldname = text;
                                    obj.form_typeid = formId; //字段所属表格或表单id
                                    obj.fieldstate = '1'; //字段状态  正常使用为1,被删除为0
                                    thnewName.push(text);
                                    var colId = ths[i].getAttribute('id'); //字段英文名称
                                    if (colId) obj.fieldenglish = colId;
                                    var sort = ths[i].getAttribute('table_sort');
                                    var query = ths[i].getAttribute('query');
                                    var sum = ths[i].getAttribute('sum');
                                    var average = ths[i].getAttribute('average');
                                    var count = ths[i].getAttribute('count');
                                    var colSum = ths[i].getAttribute('col_sum');
                                    var colAverage = ths[i].getAttribute('col_average');
                                    var colCount = ths[i].getAttribute('col_count');
                                    var dataType = ths[i].getAttribute('data_type'); //字段类型
                                    var dataLength = ths[i].getAttribute('data_length'); //字段长度
                                    var isFill = ths[i].getAttribute('isfill'); //必填
                                    var thModel = ths[i].getAttribute('model'); //内层model属性
                                    var supcontent=ths[i].getAttribute('supcontent');
                                    var fill_field=ths[i].getAttribute('fill_field');//自动填充设置

                                    if (sort) obj.sortno = sort //排序
                                    else {obj.sortno = 'null'};
                                    if (dataLength) obj.length = dataLength; //字段长度
                                    if (fill_field) obj.fill_field = fill_field;//自动填充设置
                                    if (query) obj.queryno = query; //查询
                                    if (average == '1' || sum == '1' || count == '1' || colSum ==
                                        '1' || colAverage == '1' || colCount == '1') obj.stacno =
                                        '1';
                                    else obj.stacno = '0';
                                    if (dataType) obj.datatype = dataType;
                                    if(dataType=="pulldown"){ 
                                        supcontentObj[colId]=supcontent;
                                    }
                                    if (isFill) obj.nonull = isFill;
                                    if(thModel) obj.model = thModel;
                                    grid.push(obj);
                            }
                        }
                        leipiFormDesign.setUptModel(tholdName, thnewName, template);
                        var tableModel = template.querySelector('table').getAttribute('model'); //外层model属性
                        property.formname = tablename;
                        property.html = formeditor;
                        property.supcontent=JSON.stringify(supcontentObj);
                        property.model = type == 'del' ? 'del' : tableModel;
                        property.grid = JSON.stringify(grid); //将grid数组转换成字符串
                        property.cols = JSON.stringify(cols);
                        if(tableModel != 'insert') {
                            property.tablename = basename;
                            property.id = baseid;
                        };
                        if(type == 'copy') {
                            return property;
                            return false;
                        }
                        if(type == 'save'){
                            property.type = 'save';
                        }
                        leipiFormDesign.updateForm(property);
                    } else {
                        layer.msg('表单名称不能为空', {time: 1500});
                        return false;
                    }
            } else {
                layer.msg('表单内容不能为空', {time: 1500});
                return false;
            }
        },
        setThsOrder: function(node, ths){
            var configThs = [], 
                deleteThs = [],
                th = node.querySelector('.firstRow th'),
                ut = UE.UETable.getUETable(th);
            $.each(ths, function(index, item){
                var rowspan = item ? item.getAttribute('rowspan') : 1;
                if(rowspan > 1){
                    var pos = ut.getCellInfo(item);
                    deleteThs.push({ th: item, position: pos.colIndex });
                }else{
                    configThs.push(item)
                }
            });
            $.each(deleteThs, function(kndex, ktem){
                configThs.splice(ktem.position, 0, ktem.th);
            });
            
            return configThs;
        },
        setUptModel: function(a, b, template){
            var table = template.querySelector('table');
            var ths = table.querySelectorAll('th');
            var oldModel = table.getAttribute('model');
            //判断两个数组相等
            var flag = true;
            if(!(a instanceof Array) || !(b instanceof Array)) flag = false;
            if(a.length != b.length) flag = false;
            for(var i = 0, len = b.length; i < len; i++){
                if(a.indexOf(b[i]) == -1 && b.indexOf(a[i]) == -1 && ths[i].getAttribute('model') == 'normal') {
                    flag = false;
                    ths[i].setAttribute('model', 'update');  //当th表头值改变该列为update
                }
            }
            if(flag == false && oldModel == 'normal'){ 
                table.setAttribute('model', 'update'); //当th表头值改变时外层也为update
                var newDiv = document.createElement('div');
                newDiv.innerHTML = template;
                leipiEditor.setContent(template.innerHTML);
            }
        },
        getCustomCols: function(allTrs, valueCols){
            window.customCols = [];
            $.each(allTrs, function(index, item){
                var hasTh = $(this).find('th');
                if(hasTh && hasTh.length > 0){
                    var childNodes = $(this).children(),
                        eachCols = [];
                    $.each(childNodes, function(kndex, ktem){
                        var rowspan = $(this).attr('rowspan') || 1,
                            colspan = $(this).attr('colspan') || 1,
                            title = $(this).text(),
                            params = { title: title, rowspan: rowspan, colspan: colspan };
                        valueCols.indexOf(ktem) != -1 ? params.field = $(this).attr('id') : '';
                        eachCols.push(params)
                    });
                    window.customCols.push(eachCols);
                }
            });
            return window.customCols;
        }, 
        getValueCosl: function(allTrs, ut){
            var valueCols = [];
            $.each(allTrs, function(index, item){
                var hasTh = $(this).find('th');
                if(hasTh && hasTh.length > 0){
                    var childNodes = $(this).children();
                    $.each(childNodes, function(kndex, ktem){
                        var nextCell = ut.getVSideCell(ktem, true);
                        // if(isIE()){
                        //     if(nextCell && nextCell.tagName == 'TD'){
                        //         valueCols.push(ktem);
                        //     }
                        // }else{
                        //     if(nextCell && nextCell.tagName == 'TD' && !nextCell.getAttribute('colspan')){
                        //         valueCols.push(ktem);
                        //     }
                        // }
                        if($(ktem).attr("data_type")){
                            valueCols.push(ktem);
                        }
                    });
                }
            });
            return valueCols;
        },
        getValueThs: function(node){
            var th = node.querySelector('.firstRow th'),
                allTrs = $(node).find('tr'),
                ut = UE.UETable.getUETable(th),
                valueThs = [];
            $.each(allTrs, function(index, item){
                var hasTh = $(this).find('th');
                if(hasTh && hasTh.length > 0){
                    var childNodes = $(this).children();
                    $.each(childNodes, function(kndex, ktem){
                        var nextCell = ut.getVSideCell(ktem, true);
                        // if(isIE()){
                        //     if(nextCell && nextCell.tagName == 'TD'){
                        //         valueThs.push(ktem);
                        //     }
                        // }else{
                        //     if(nextCell && nextCell.tagName == 'TD' && !nextCell.getAttribute('colspan')){
                        //         valueThs.push(ktem);
                        //     }
                        // }
                        if(isIE()){
                            if($(ktem).attr("data_type")){
                                    valueThs.push(ktem);
                                }
                        }else{
                            if($(ktem).attr("data_type")){
                                valueThs.push(ktem);
                            }
                        }
                    });
                }
            });
            return valueThs;
        },
        getCols: function(node){
            var th = node.querySelector('.firstRow th'),
                allTrs = $(node).find('tr'),
                ut = UE.UETable.getUETable(th);
            var valueCols = leipiFormDesign.getValueCosl(allTrs, ut), 
                cols = leipiFormDesign.getCustomCols(allTrs, valueCols); 

            return cols;
        }
    };
</script>
</body>
<style>
    .formTreeList{
        padding-top: 5px;
    }
    .left-tree-part{
        width: 25%;
        float: left;
    }
    .myFormView{
        width: 75%;
        float: right;
    }
    .btns{
        padding-left: 10px;
        margin: 5px 0;
    }
    .layui-btn-confirm{
        background-color: #2669B1;
    }
    .myFormView .edui-editor{
        height: 432px;
    }
    .myFormView .edui-editor-iframeholder {
        height: 429px !important;
    }
    .left-tree-part .ztree{
        height: 390px;
        overflow: scroll;
    }
</style>
<div class="formTreeList clearfix" style="display: none;">
    <div class="left-tree-part">
        <div class="btns">
            <button class="layui-btn layui-btn-sm layui-btn-confirm" id="insertForm">确认选择</button>
        </div>
        <ul id="treeDemo" class="ztree"></ul>
    </div>
    <div id="myFormView" class="myFormView edui-default" style="height: 200px;">

    <script type="text/javascript">
        var leipiEditor2 = UE.getEditor('myFormView', {
            allowDivTransToP: false, //阻止转换div 为p
            toolleipi: true, //是否显示，设计器的 toolbars
            textarea: 'design_content',
            //这里可以选择自己需要的工具按钮名称,此处仅选择如下五个
            toolbars: [],
            //focus时自动清空初始化时的内容
            //autoClearinitialContent:true,
            //关闭字数统计
            wordCount: false,
            //关闭elementPath
            elementPathEnabled: false,
            //默认的编辑区域高度
            initialFrameHeight: 450
            ,iframeCssUrl:"css/bootstrap/css/bootstrap.css" 
        });
    </script>
</div>

</html>
